package com.sgb.goods.viewmodel;

import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.lifecycle.MutableLiveData;

import com.blankj.utilcode.util.ClipboardUtils;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.api.GoodsCallBack;
import com.sgb.goods.api.GoodsNet;
import com.sgb.goods.entity.ContractStateEntity;
import com.sgb.goods.entity.LogisticsDetailEntity;
import com.sgb.goods.entity.OrderDetailsEntity;
import com.sgb.goods.entity.OrderDynamicEntity;
import com.sgb.goods.entity.OrderNoticeEntity;
import com.sgb.goods.utils.StringUtils;
import com.sgb.goods.utils.base.adapter.BaseCommonAdapter;
import com.sgb.goods.utils.base.viewmodel.BaseViewModel;
import com.sgb.goods.utils.module.GoodsModule;
import com.sgb.goods.view.adapter.SellOrderDetailsAdapter;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 销售订单详情
 *
 * @author cyj
 */
public class SellOrderDetailsViewModel extends BaseViewModel {

    public SellOrderDetailsAdapter adapter;
    public BaseCommonAdapter<OrderDetailsEntity.OrderDynamicEntity> dynamicsAdapter;
    public OrderNoticeEntity orderNoticeEntity;
    /**
     * 是否展开订单信息view
     */
    public ObservableBoolean isOpenOrderInfo = new ObservableBoolean(false);
    /**
     * 是否展开订单商品信息view
     */
    public ObservableBoolean isOpenGoodsInfo = new ObservableBoolean(false);
    /**
     * 商品金额合计
     */
    public ObservableField<String> goodsPriceTotal = new ObservableField<>("0.00");
    /**
     * 订单金额合计
     */
    public ObservableField<String> orderPriceTotal = new ObservableField<>("0.00");
    /**
     * 合同状态
     */
    public ObservableInt contractState = new ObservableInt(3);
    /**
     * 合同最新状态-提示
     */
    public ObservableField<ContractStateEntity> contractStateEntity = new ObservableField<>();
    public ObservableField<OrderDetailsEntity> orderDetailsEntity = new ObservableField<>(new OrderDetailsEntity());
    public MutableLiveData<String> titleName = new MutableLiveData<>();
    public MutableLiveData<List<OrderDynamicEntity.OrderDynamicRecords>> orderDynamicRecordsList = new MutableLiveData<>();
    public MutableLiveData<LogisticsDetailEntity> logisticsDetailEntity = new MutableLiveData<>();

    public SellOrderDetailsViewModel() {
        adapter = new SellOrderDetailsAdapter(R.layout.goods_item_purchase_order_details, BR.entity);
        dynamicsAdapter = new BaseCommonAdapter<>(R.layout.goods_item_dynamics, BR.viewModel);
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单id
     */
    public void getOrderDetail(String orderId) {
        showLoading();
        GoodsNet.getInstance().getGoodsApi().getOrderDetail(orderId, "2").enqueue(new GoodsCallBack<BaseEntity<OrderDetailsEntity>>() {
            @Override
            public void onSuccess(BaseEntity<OrderDetailsEntity> data) {
                // 获取合同状态
                getContractState(data.getData());
                // 初始化 设置审批描述 && 获取初始化订单信息所有日期时间串 && 订单详情数据 && 获取商品金额总计
                data.getData().init("2");
                orderDetailsEntity.set(data.getData());
                getGoodsPriceTotal(data.getData());
                // 设置title
                titleName.setValue(data.getData().titleName);
                // 订单信息数据集填充
                adapter.setNewData(data.getData().commodities);
                adapter.showThreeItem(true);
                adapter.notifyDataSetChanged();
                dynamicsAdapter.setNewData(data.getData().dynamicEntityList);
                // 获取订单通知提示信息
                getOrderNoticeInfo();
            }
        });
    }

    /**
     * 获取商品金额总计 && 订单金额合计
     */
    private void getGoodsPriceTotal(OrderDetailsEntity orderDetailsEntity) {
        // 获取商品金额总计
        BigDecimal bd = new BigDecimal(0);
        for (OrderDetailsEntity.OrderCommoditiesEntity entity : orderDetailsEntity.commodities) {
            bd = bd.add(BigDecimal.valueOf(entity.total));
        }
        goodsPriceTotal.set(bd.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        // 订单金额合计
        bd = bd.add(StringUtils.convertStrToBD(orderDetailsEntity.deliveryCost))
                .add(StringUtils.convertStrToBD(orderDetailsEntity.handlingCost))
                .add(StringUtils.convertStrToBD(orderDetailsEntity.installationCost));
        orderPriceTotal.set(bd.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }

    /**
     * 获取合同状态
     */
    public void getContractState(OrderDetailsEntity orderDetailsEntity) {
        showLoading();
        String companyNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, "");
        GoodsNet.getInstance().getGoodsApi().getContractState(String.valueOf(orderDetailsEntity.id), companyNo)
                .enqueue(new GoodsCallBack<BaseEntity<ContractStateEntity>>() {
                    @Override
                    public void onSuccess(BaseEntity<ContractStateEntity> data) {
                        contractState.set(data.getData().contractState);
                        contractStateEntity.set(data.getData());
                    }
                });
    }

    /**
     * 设置是否展开订单信息 点击事件
     */
    public void setOpenOrderInfoForOnClick() {
        this.isOpenOrderInfo.set(!this.isOpenOrderInfo.get());
    }

    /**
     * 设置是否展开订单商品信息 点击事件
     */
    public void setOpenGoodsInfoForOnClick() {
        this.isOpenGoodsInfo.set(!this.isOpenGoodsInfo.get());
        adapter.showThreeItem(!this.isOpenGoodsInfo.get());
    }

    /**
     * 复制订单号到粘贴板 点击事件
     */
    public void copyToClipboard() {
        ClipboardUtils.copyText(String.valueOf(orderDetailsEntity.get().id));
        MToast.showToast(application.getApplicationContext(), "复制成功");
    }

    /**
     * 供应商-跳转企业网站 点击事件
     */
    public void startWebsiteInfoActivity() {
        if (Objects.requireNonNull(orderDetailsEntity.get()).orderType == 1) {
            GoodsModule.getInstance().call1("jumpWebsiteInfoActivity", orderDetailsEntity.get().owned, 1);
        } else if (Objects.requireNonNull(orderDetailsEntity.get()).orderType == 0) {
            GoodsModule.getInstance().call1("jumpWebsiteInfoActivity", orderDetailsEntity.get().person, 0);
        }
    }

    /**
     * 获取订单动态数据集
     */
    public void getOrderDynamicInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderDetailsEntity.get().id);
        map.put("pageSize", 20);
        map.put("owned", orderDetailsEntity.get().owned);
        map.put("state", orderDetailsEntity.get().state);
        // 订单类型 1 销售订单 2 采购订单
        map.put("type", "1");
        map.put("pageNum", 1);
        showLoading();
        GoodsNet.getInstance().getGoodsApi().getOrderDynamicInfo(map).enqueue(new GoodsCallBack<BaseEntity<OrderDynamicEntity>>() {
            @Override
            public void onSuccess(BaseEntity<OrderDynamicEntity> data) {
                orderDynamicRecordsList.setValue(data.getData().records);
            }
        });
    }

    /**
     * 待收货、已收货 点击查询物流详情并弹窗
     */
    public void getLogisticsInfo() {
        if (2 == orderDetailsEntity.get().deliverState) {
            // 待收货没有物流信息，因此不含有点击事件
            return;
        }
        showLoading();
        GoodsNet.getInstance().getGoodsApi().getDeliverByOrderId(String.valueOf(orderDetailsEntity.get().id))
                .enqueue(new GoodsCallBack<BaseEntity<List<LogisticsDetailEntity.Record>>>() {
                    @Override
                    public void onSuccess(BaseEntity<List<LogisticsDetailEntity.Record>> data) {
                        logisticsDetailEntity.setValue(new LogisticsDetailEntity(orderDetailsEntity.get().supplierName,
                                String.valueOf(orderDetailsEntity.get().id), data.getData()));
                    }
                });
    }

    /**
     * 获取订单通知信息
     */
    private void getOrderNoticeInfo() {
        if (3 != orderDetailsEntity.get().orderProcessState) {
            return;
        }
        showLoading();
        GoodsNet.getInstance().getGoodsApi().getNotice(String.valueOf(orderDetailsEntity.get().id), "2")
                .enqueue(new GoodsCallBack<BaseEntity<OrderNoticeEntity>>() {
                    @Override
                    public void onSuccess(BaseEntity<OrderNoticeEntity> data) {
                        // null == data.getData() 表示需要app自己判断默认代办提示,否则进入代办提示判断
                        orderDetailsEntity.get().approvalDesc.set(
                                null == data.getData() ?
                                        1 == orderDetailsEntity.get().paymentWay ? "请等待采购商付款后进行发货" : "请进行发货，发货后供应商将支付货款" :
                                        data.getData().getStateString(orderDetailsEntity.get().paymentMethod));
                        orderNoticeEntity = data.getData();
                    }
                });
    }
}
